<template>
  <div>
    <div v-if="tableVisible">
      <a-table
        :pagination="false"
        :data-source="tableData"
        :scroll="{ x: 1500 }"
        bordered
        :loading="tableLoading"
        size="small"
      >
        <a-table-column v-for="item in columns" :key="item.dataIndex" :data-index="item.dataIndex" :width="item.width" :ellipsis="item.ellipsis">
          <span slot="title">
            <a-input v-if="tableEdit && item.title !== '序号' && item.title !== 'the_geom'" v-model="item.title"></a-input>
            <span v-else>{{ item.title }}</span>
          </span>
        </a-table-column>
      </a-table>
    </div>
  </div>
</template>

<script>
import {baseDataTableList, baseDataTableListUpdate} from '@/api/modular/main/tsdatarecord/baseDataTable'
import { metadataPage } from '@/api/modular/main/tsdatarecord/timeSpaceDataRecordManage'
export default {
  name: 'uploadDataTable',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    editHeader: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      columns: [],
      tableData: [],
      tableVisible: false,
      tableEdit: false,
      tableLoading: false,
      recordId: ''
    }
  },
  watch: {
    visible(v) {
      this.tableVisible = v
    },
    editHeader(v) {
      this.tableEdit = v
    }
  },
  methods: {
    init(recordId) {
      this.tableEdit = false
      this.recordId = recordId
      this.loadData()
    },
    loadData() {
      const { recordId } = this
      baseDataTableList({ recordId: recordId }).then(res => {
        if (res.success) {
          this.columns = []
          this.columns.push({
            title: '序号',
            width: 50,
            fixed: 'left',
            dataIndex: 'key'
          })
          res.data.forEach(col => {
            if (col.title === 'the_geom') {
              col.ellipsis = true
            }
            this.columns.push(col)
          })
          this.tableVisible = true
          metadataPage({ recordId: recordId, pageNo: 1, pageSize: 5 }).then(res => {
            if (res.success) {
              this.tableData = []
              for (let i = 0; i < res.data.rows.length; i++) {
                res.data.rows[i] = JSON.parse(res.data.rows[i].content)
                res.data.rows[i].key = i + 1
                this.tableData.push(res.data.rows[i])
              }
            }
          })
        }
      })
    },
    save() {
      const body = _.filter(this.columns, (c) => { return c.id !== undefined })
      baseDataTableListUpdate(body).then((res) => {
        if (res.success) {
          this.$message.success('修改完成！')
        } else {
          this.$message.warning('修改失败！')
        }
        this.$emit('update')
        this.loadData()
      }).catch(() => {
        this.$message.warning('修改失败！')
      })
    }
  }
}
</script>

<style scoped>
</style>
